<template>
  <BasicDrawer
    v-bind="$attrs"
    :width="drawerWidth"
    :title="title"
    :show-footer="true"
    @register="registerInnerDrawer"
    @ok="handleSubmit"
    @close="resetForm"
  >
    <BasicForm @register="registerForm"></BasicForm>
  </BasicDrawer>
</template>

<script setup lang="ts">
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicForm, useForm } from '@/components/Form';
  import { computed, ref, unref } from 'vue';
  import { addCustomerAddress, updateCustomerAddress } from '@/api/customer';
  import { drawerSchemas } from './address.data';
  import { useMaxWidthOrDefault } from '@/hooks/web/useSize';
  defineOptions({ name: 'AddressDrawer' });

  const emit = defineEmits(['register', 'reload']);

  const isUpdate = ref<boolean>(false);
  const drawerWidth = useMaxWidthOrDefault(700);
  const title = computed<string>(() => {
    return isUpdate.value ? '编辑地址' : '新增地址';
  });

  const [registerInnerDrawer, { drawerLoading, closeDrawer }] = useDrawerInner(
    async (data: { record?: Recordable; update: boolean; customerId: string }) => {
      drawerLoading(true);
      const { record, update, customerId } = data;
      isUpdate.value = update;
      if (record) {
        setFieldsValue({
          ...record,
          area: [record.addressProvince, record.addressCity],
          addressCustomerId: customerId,
        });
      } else {
        setFieldsValue({
          addressCustomerId: customerId,
        });
      }
      drawerLoading(false);
    },
  );

  const [registerForm, { setFieldsValue, resetForm, validate }] = useForm({
    // layout: 'vertical',
    labelWidth: 100,
    name: 'address-drawer',
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
    schemas: drawerSchemas,
  });
  async function handleSubmit() {
    try {
      drawerLoading(true);
      const data = await validate();
      if (unref(isUpdate)) {
        await updateCustomerAddress({
          ...data,
          addressProvince: data.area[0],
          addressCity: data.area[1],
          addressIsEmailAddress: data.addressIsEmailAddress ? 1 : 0,
        });
      } else {
        await addCustomerAddress({
          ...data,
          addressProvince: data.area[0],
          addressCity: data.area[1],
          addressIsEmailAddress: data.addressIsEmailAddress ? 1 : 0,
        });
      }
      emit('reload');
      closeDrawer();
      await resetForm();
    } catch (e) {
      console.log('e', e);
    } finally {
      drawerLoading(false);
    }
  }
</script>
